#!/usr/bin/env python
from astropy.table import Table
import numpy as np
import sys
import matplotlib.pyplot as plt

tab = Table.read(sys.argv[1],format='ipac')
gain = tab['gain'].data
channel = tab['channel'].data
wave = tab['wave'].data
non_linear = tab['nlptc20'].data
c_unique = np.unique(channel)
c_unique = np.delete(c_unique,0)
w_unique = np.unique(wave)
w_unique = np.delete(w_unique,len(w_unique)-1)
NL = np.zeros((len(w_unique),len(c_unique)))
#print(w_unique,abs(wave-650)>10)
for i in range(len(c_unique)):
    #print(channel==c_unique[i])
    # print(int(sys.argv[2]))
    if int(sys.argv[2]) == 0:
#        idx = np.where((channel==c_unique[i])*(abs(wave-int(sys.argv[3]))>30)) #红外
       idx = np.where((channel==c_unique[i])*(wave<=400))  #紫外
        # idx = np.where((channel==c_unique[i])*(wave>400))  #可见
    else:
        idx = np.where((channel==c_unique[i]))
    c_idx = np.where(channel==c_unique[i])
    gain_c = gain[idx]
    #print("gain_c",gain_c)
    tab['gain_diff'][idx] = (np.max(gain_c)-np.min(gain_c))/np.mean(gain_c)*100
    #NL[:,i] = non_linear[c_idx][np.argsort(wave[c_idx])]
tab.write(sys.argv[1],format='ipac',overwrite=True)
#for i in range(len(w_unique)):
#    plt.plot(np.arange(16)+1,NL[i,:],label=str(w_unique[i])+" nm",linestyle='--')
#    plt.scatter(np.arange(16)+1,NL[i,:],s=20)
#plt.xlabel("channel")
#plt.ylabel("nlptc20 [%]")
#plt.xticks(np.arange(16)+1)
#plt.legend()
#plt.title(sys.argv[2]+" nlptc20")
#plt.savefig("nlptc20.jpg")
#plt.show()
